/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yuhanginfo.modules.sys.web;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.utils.FileUtils;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.sys.entity.Classes;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.GoodsCombDetail;
import com.yuhanginfo.modules.sys.entity.GoodsCombo;
import com.yuhanginfo.modules.sys.entity.OrdersDetail;
import com.yuhanginfo.modules.sys.service.ClassesService;
import com.yuhanginfo.modules.sys.service.GoodsCombDetailService;
import com.yuhanginfo.modules.sys.service.GoodsCombStoreService;
import com.yuhanginfo.modules.sys.service.GoodsComboService;
import com.yuhanginfo.modules.sys.service.GoodsService;
import com.yuhanginfo.modules.sys.service.OrdersDetailService;
import com.yuhanginfo.modules.sys.utils.CodeUtil;
import com.yuhanginfo.modules.sys.utils.UserUtils;

/**
 * 商品套餐Controller
 * @author lvls
 * @version 2017-11-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/goodsCombo")
public class GoodsComboController extends BaseController {

	@Autowired
	private GoodsComboService goodsComboService;
	
	@Autowired
	private ClassesService classesService;
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsCombDetailService combDetailService;
	
	@Autowired
	private GoodsCombStoreService goodsCombStoreService;
	
	@Autowired
	private OrdersDetailService orderDetailService;
	
	private static final String FIRSTCLASS = "firstClass";
	private static final String GOODS = "goods";
	private static final String DETAIL = "detail";
	private static final String REDIRECT = "redirect:"+Global.getAdminPath()+"/sys/goodsCombo/?repage";
	@ModelAttribute
	public GoodsCombo get(@RequestParam(required=false) String id) {
		GoodsCombo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = goodsComboService.get(id);
		}
		if (entity == null){
			entity = new GoodsCombo();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = {"list", ""})
	public String list(GoodsCombo goodsCombo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<GoodsCombo> page = goodsComboService.findPage(new Page<GoodsCombo>(request, response), goodsCombo);
		model.addAttribute("page", page);
		return "modules/sys/goodsCombo/goodsComboList";
	}

	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "form")
	public String form(GoodsCombo goodsCombo, Model model, HttpServletRequest request, HttpServletResponse response) {
		List<Classes> firstClass = classesService.selectFirstClass();
		Goods goods = new Goods();
		Page<Goods> page = new Page<>(request, response);
		page.setPageSize(5);
		page.setPageNo(0);
		Page<Goods> goodsList = goodsService.selectPageGoodsByMateriel(page, goods);
		model.addAttribute("page", goodsList);
		model.addAttribute(FIRSTCLASS, firstClass);
		model.addAttribute(GOODS, goods);
		return "modules/sys/goodsCombo/goodsComboForm";
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "edit")
	public String edit(GoodsCombo goodsCombo, Model model, HttpServletRequest request, HttpServletResponse response) {
		List<Classes> firstClass = classesService.selectFirstClass();
		List<GoodsCombDetail> goodsCombDetails = combDetailService.selectByGoodsComboId(goodsCombo.getId());
		Goods goods = new Goods();
		Page<Goods> page = new Page<>(request, response);
		page.setPageSize(5);
		page.setPageNo(0);
		Page<Goods> goodsList = goodsService.selectPageGoodsByMateriel(page, goods);
		model.addAttribute("goodsCombDetails", goodsCombDetails);
		model.addAttribute("goodsCombo", goodsCombo);
		model.addAttribute("page", goodsList);
		model.addAttribute(FIRSTCLASS, firstClass);
		model.addAttribute(GOODS, goods);
		return "modules/sys/goodsCombo/goodsComboEdit";
	}

	@RequiresPermissions("sys:goodsCombo:edit")
	@RequestMapping(value = "save")
	public String save(GoodsCombo goodsCombo,@RequestParam("file") MultipartFile[] file,
			Model model,HttpServletRequest request, RedirectAttributes redirectAttributes, HttpSession session) {
		String[] goodsId = request.getParameterValues("goodsId");
		String[] goodsCode = request.getParameterValues("goodsCode");
		String[] goodsName = request.getParameterValues("goodsName");
		String[] oldPrice = request.getParameterValues("oldPrice");
		String[] goodsPrice = request.getParameterValues("goodsPrice");
		String[] num = request.getParameterValues("num");
		StringBuilder path = new StringBuilder();
		try {
			for (MultipartFile f : file) {
				String originalFilename = f.getOriginalFilename();
				path.append(FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), originalFilename, f.getInputStream()));
				path.append(";");
			}
		} catch (Exception ex) {
			logger.info("save", ex);
		}
		String[] split = path.toString().split(";");
		String goodsComboCode = CodeUtil.getGoodsComboCode();
		goodsCombo.setCode(goodsComboCode);
		goodsCombo.setPhoto(split[0]);
		String detail = (String) session.getAttribute(DETAIL);
		goodsCombo.setRemarks(detail);
		session.removeAttribute(DETAIL);
		goodsCombo.setStatus(0);
		goodsCombo.setIsHistory(0);
		goodsComboService.save(goodsCombo);
		for (int i = 0; i < goodsId.length; i++) {
			GoodsCombDetail combDetail = new GoodsCombDetail();
			combDetail.setGoodsCombId(goodsCombo.getId());
			combDetail.setGoodsName(goodsName[i]);
			combDetail.setGoodsCode(goodsCode[i]);
			combDetail.setOldPrice(BigDecimal.valueOf(Double.valueOf(oldPrice[i])));
			combDetail.setPrice(BigDecimal.valueOf(Double.valueOf(goodsPrice[i])));
			combDetail.setVipPrice(BigDecimal.valueOf(Double.valueOf(goodsPrice[i])));
			combDetail.setNum(Integer.parseInt(num[i]));
			combDetailService.save(combDetail);
		}
		addMessage(redirectAttributes, "保存商品套餐成功");
		return REDIRECT;
	}
	
	@RequiresPermissions("sys:goodsCombo:edit")
	@RequestMapping(value = "editSave")
	public String editSave(GoodsCombo goodsCombo,@RequestParam("file") MultipartFile[] file,
			Model model, HttpServletRequest request,RedirectAttributes redirectAttributes,HttpSession session) {
		String[] goodsId = request.getParameterValues("goodsId");
		String[] goodsCode = request.getParameterValues("goodsCode");
		String[] goodsName = request.getParameterValues("goodsName");
		String[] oldPrice = request.getParameterValues("oldPrice");
		String[] vipPrice = request.getParameterValues("vipPrice");
		String[] goodsPrice = request.getParameterValues("goodsPrice");
		String[] num = request.getParameterValues("num");
		StringBuilder path = new StringBuilder();
		//创建一个新套餐数据，并将之前的套餐数据设为历史记录
		GoodsCombo newGoodsCombo = new GoodsCombo();
		try {
			for (MultipartFile f : file) {
				String originalFilename = f.getOriginalFilename();
				String saveSimpleNewImage = FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), originalFilename, f.getInputStream());
				path.append(saveSimpleNewImage);
				path.append(";");
			}
		} catch (Exception ex) {
			logger.info("editSave",ex);
		}
		String[] split = path.toString().split(";");
		if(!"null".equals(split[0])){
			newGoodsCombo.setPhoto(split[0]);
		}else{
			newGoodsCombo.setPhoto(goodsCombo.getPhoto());
		}
		String detail = (String) session.getAttribute(DETAIL);
		session.removeAttribute(DETAIL);
		newGoodsCombo.setRemarks(this.formatImg(goodsCombo.getDeleteDetail(),goodsCombo.getRemarks(),detail));
		String goodsComboCode = CodeUtil.getGoodsComboCode();
		newGoodsCombo.setCode(goodsComboCode);
		newGoodsCombo.setName(goodsCombo.getName());
		newGoodsCombo.setPrice(goodsCombo.getPrice());
		newGoodsCombo.setStatus(0);
		newGoodsCombo.setIsHistory(0);
		//创建一个新数据
		goodsComboService.save(newGoodsCombo);
		for (int i = 0; i < goodsId.length; i++) {
			GoodsCombDetail combDetail = new GoodsCombDetail();
			combDetail.setGoodsCombId(newGoodsCombo.getId());
			combDetail.setGoodsName(goodsName[i]);
			combDetail.setGoodsCode(goodsCode[i]);
			combDetail.setOldPrice(BigDecimal.valueOf(Double.valueOf(oldPrice[i])));
			combDetail.setPrice(BigDecimal.valueOf(Double.valueOf(goodsPrice[i])));
			combDetail.setVipPrice(BigDecimal.valueOf(Double.valueOf(vipPrice[i])));
			combDetail.setNum(Integer.parseInt(num[i]));
			combDetailService.save(combDetail);
		}	
		goodsComboService.setHistoryByGoodsComboCode(goodsCombo);
		goodsCombStoreService.setHistoryByGoodsComboCode(goodsCombo);
		addMessage(redirectAttributes, "保存商品套餐成功");
		return REDIRECT;
	}
	
	@RequiresPermissions("sys:goodsCombo:edit")
	@RequestMapping(value = "delete")
	public String delete(GoodsCombo goodsCombo, RedirectAttributes redirectAttributes) {
		goodsComboService.delete(goodsCombo);
		addMessage(redirectAttributes, "删除商品套餐成功");
		return REDIRECT;
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "getClassByParentId")
	@ResponseBody
	public List<Classes> getClassByParentId(String parentId, RedirectAttributes redirectAttributes) {
		return classesService.twiceClassList(parentId);
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "selectGoodsByIds")
	@ResponseBody
	public List<Goods> selectGoodsByIds(String[] checkedGoods, RedirectAttributes redirectAttributes) {
		return goodsService.selectGoodsByIds(checkedGoods);
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "selectGoodsComDetail")
	@ResponseBody
	public List<GoodsCombDetail> selectGoodsComDetail(GoodsCombDetail goodsCombDetail, RedirectAttributes redirectAttributes) {
		return combDetailService.findList(goodsCombDetail);
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "searchGoods")
	public String searchGoods(Goods goods, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Goods> page = goodsService.selectPageGoodsByMateriel(new Page<Goods>(request, response), goods);
		List<Classes> firstClass = classesService.selectFirstClass();
		model.addAttribute("page", page);
		model.addAttribute(FIRSTCLASS, firstClass);
		model.addAttribute(GOODS, new Goods());
		return "modules/sys/goodsCombo/showGoods";
	}
	
	@RequiresPermissions("sys:goodsCombo:view")
	@RequestMapping(value = "couldDelete")
	@ResponseBody
	public String couldDelete(String goodsComboId, HttpServletRequest request, HttpServletResponse response, Model model) {
		GoodsCombo goodsCombo = goodsComboService.get(goodsComboId);
		if(goodsCombo.getStatus()==1){
			return "couldNotDelete";
		}
		List<OrdersDetail> list = orderDetailService.selectByGoodsComboCode(goodsCombo.getCode());
		if(!list.isEmpty()){
			return "couldNotDelete";
		}
		return "couldDelete";
	}
	
	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "saveDetail")
	@ResponseBody
	public String saveDetail(@RequestParam("file") MultipartFile[] file, HttpSession session) {
		StringBuilder path = new StringBuilder();
		try {
			int i = 0;
			for (MultipartFile f : file) {
				if( i > 0 ){
					path.append(";");
				}
				path.append(FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), f.getOriginalFilename(), f.getInputStream()));
				i++;
			}
		} catch (Exception ex) {
			logger.info("saveDetail",ex);
		}
		session.setAttribute(DETAIL, path.toString());
		return "true";
	}
	
	//对比文件名，将未删除的文件和新上传的文件组合保留
	public String formatImg(String delImg,String oldImg,String newImg){
		String finalImg = "";
		if( null!=delImg && !"".equals(delImg) && null!=oldImg && !"".equals(oldImg)){
			String[]  delImgArray = delImg.split(";");
			String[]  oldImgArray = oldImg.split(";");
			for(int i=0;i<oldImgArray.length;i++){
				boolean delFlag = true;
				for(int y=0;y<delImgArray.length;y++){
					if(oldImgArray[i].substring(oldImgArray[i].lastIndexOf('/')+1, oldImgArray[i].lastIndexOf('.')).equals(delImgArray[y])){
						delFlag = false;
						break;
					}
				}
				if(delFlag){
					if(i>0){
						finalImg += ";";
					}
					finalImg += oldImgArray[i];
				}
			}
		}else if( null!=oldImg && !"".equals(oldImg)){
			finalImg += oldImg;
		}
		if( null!=newImg && !"".equals(newImg)){
			if(finalImg != null && !"".equals(finalImg)){
				finalImg += ';';
			}
			finalImg += newImg;
		}
		return finalImg;
	}
}